﻿#region

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using JsMapper.BL;
using JsMapper.BL.Config;
using JsMapper.BO;

#endregion

namespace JsMapper.StandaloneExporter
{
    public static class Exporter
    {
        private static bool IsAlreadyConfigured { get; set; }

        private static void ConfigurateJsModelManager(string assemblyFile)
        {
            if (IsAlreadyConfigured) return;

            JsModelManager.ConfigMngr.Configurate(
                new JsModelFluentConfig()
                    .ScanForViewModels(assemblyFile)
                );

            IsAlreadyConfigured = true;
        }

        private static IEnumerable<KeyValuePair<string, string>> GetClassNameWithOutput(string assemblyPath, string outputPath, bool wrapOutput, IJsModelMapper mapper)
        {
            ConfigurateJsModelManager(assemblyPath);

            foreach (var model in JsModelManager.ModelRepository.GetAll())
            {
                var modelOutput = wrapOutput ?
                                      JsModelManager.GetJsOutput(mapper, model.ModelType) :
                                      mapper.GetJs(model);

                yield return new KeyValuePair<string, string>(model.Name, modelOutput);
            }
        }

        public static void Export1FilePerModel(string assemblyPath, string outputPath, bool wrapOutput, IJsModelMapper mapper, string fileExt = "js")
        {
            foreach (var classNameWithOutput in GetClassNameWithOutput(assemblyPath, outputPath, wrapOutput, mapper))
            {
                var filePath = string.Format("{0}\\{1}.{2}", outputPath, classNameWithOutput.Key, fileExt);
                File.WriteAllText(filePath, classNameWithOutput.Value);
            }
        }

        public static void Export1File(string assemblyPath, string outputPath, bool wrapOutput, IJsModelMapper mapper)
        {
            var file = GetClassNameWithOutput(assemblyPath, outputPath, wrapOutput, mapper).Aggregate(string.Empty, (current, classNameWithOutput) => current + (classNameWithOutput.Value + Environment.NewLine));
            File.WriteAllText(outputPath, file);
        }
    }
}